import fs from "fs";
import path from "path";
import { fileURLToPath, URL } from 'node:url';
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite';
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';

const date = new Date();
const version = [date.getFullYear(),
date.getMonth() + 1,
date.getDate(),
date.getHours(),
date.getMinutes(),
date.getSeconds()].map(t => {
  return t > 9 ? t : '0' + t;
}).join('');

function deleteContentsOfDirectory(dirPath) {
  if (fs.existsSync(dirPath)) {
    fs.readdirSync(dirPath).forEach((file) => {
      const filePath = path.join(dirPath, file);
      const fileStat = fs.statSync(filePath);
      if (fileStat.isDirectory()) {
        // 如果是目录，递归删除其内容
        deleteContentsOfDirectory(filePath);
        // 删除空目录
        fs.rmdirSync(filePath);
      } else {
        // 如果是文件，直接删除
        fs.unlinkSync(filePath);
      }
    });
  }
}

// https://vitejs.dev/config/
export default ({ command, mode }) => {
  if (command === "build") {
    deleteContentsOfDirectory(mode === "development" ? "web-dev" : "web-prod");
  }
  return defineConfig({
    plugins: [
      vue(),
      AutoImport({
        resolvers: [ElementPlusResolver()]
      }),
      Components({
        resolvers: [ElementPlusResolver({
          importStyle: "sass",
        })]
      }),
    ],
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `@use "@/assets/scss/elementPlus/element.scss" as *;`,
        },
      },
    },
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url))
      }
    },
    server: {
      host: '0.0.0.0'
    },
    build: {
      outDir: mode === "development" ? `web-dev/${version}` : `web-prod/${version}`
    }
  });
}
